package com.pet.backend.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pet.backend.pojo.Car;
import com.pet.backend.pojo.Vo;
import com.pet.backend.service.impl.CarServiceImpl;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wdmacke
 * @since 2024-07-20
 */
@CrossOrigin
@RestController
@RequestMapping("/car")
public class CarController {

    @Resource
    private CarServiceImpl carService;

    // 新增购物车
    @PostMapping("/insert")
    public Vo<Car> insert(@RequestBody Car car) {
        // 先查询该用户是否已经添加过
        LambdaQueryWrapper<Car> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Car::getUId, car.getUId());
        wrapper.eq(Car::getSId, car.getSId());
        Car serviceOne = carService.getOne(wrapper);
        if (serviceOne == null) {
            // 表示没有添加过
            boolean b = carService.save(car);
            if (b) {
                return new Vo<>(b, "添加成功！");
            } else {
                return new Vo<>(b, "添加失败，请稍后重试！");
            }
        } else {
            // 表示已经添加过了，更新数量
            serviceOne.setCount(serviceOne.getCount() + 1);
            BigDecimal count = BigDecimal.valueOf(serviceOne.getCount());
            serviceOne.setPrice(serviceOne.getPrice().multiply(count));
            boolean b = carService.updateById(serviceOne);
            if (b) {
                return new Vo<>(b, "添加成功！");
            } else {
                return new Vo<>(b, "添加失败，请稍后重试！");
            }
        }
    }

    // 删除购物车
    @GetMapping("/delete/{id}")
    public Vo<Car> delete(@PathVariable("id") String id) {
        LambdaQueryWrapper<Car> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Car::getId, id);
        boolean b = carService.remove(wrapper);
        if (b) {
            return new Vo<>(b, "删除该商品成功！");
        } else {
            return new Vo<>(b, "删除商品失败，请稍后重试！");
        }
    }

    // 按照用户查询
    @GetMapping("/query/{uid}")
    public Vo<Car> query(@PathVariable("uid") String uid) {
        LambdaQueryWrapper<Car> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Car::getUId, uid);
        List<Car> list = carService.list(wrapper);
        if (list.size() == 0) {
            // 表示用户购物车中没有商品
            return new Vo<>(false, "目前你的购物车中，暂无商品！");
        } else {
            return new Vo<>(true, list);
        }
    }

    // 修改购物车数据
    @PostMapping("/update")
    public Vo<Car> update(@RequestBody Car car) {
        boolean b = carService.updateById(car);
        if (b){
            return new Vo<>(b,"");
        }else {
            return new Vo<>(b,"");
        }
    }

}
